# %%
# data uitls
pacman::p_load(data.table, tidyverse, rio)
#  panel / factor model packages
pacman::p_load(synthdid)
set.seed(42)
if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
}

# Set up the analysis data
raw = rio::import(file.path(root, "/modified_data/ctcl.dta")) %>% setDT
raw[, treated := ifelse((amount > 0) & policy_year == 2016, 1, 0)]
raw = raw[policy_year <= 2016, ]

# Estimate a palcebo effect of grant receipt on Dem vote share in 2016
# using many synth alternatives
allsynth_dem2016 = panel_estimate(raw,
    "fips", "policy_year", "treated", "vs_dem_pres",
  methods=c("DID", "Time Weighted DID", 
    "DIFP (Regularized)", "Synthetic DID (SDID)"), 
  mccores = 14, reps = 1000,
  infmethod = "bootstrap")

# Estimate a palcebo effect of grant receipt on turnout in 2016
# using many synth alternatives
allsynth_tur2016 = panel_estimate(raw,
    "fips", "policy_year", "treated", "turnout_pres",
  methods=c("DID", "Time Weighted DID", 
    "DIFP (Regularized)", "Synthetic DID (SDID)"), 
  mccores = 15, reps = 1000,
  infmethod = "bootstrap")

# Save the placebo effect estimates
save(allsynth_dem2016, allsynth_tur2016, 
  file = file.path(root, "tmp/allsynth2016.RData"))

